import 'package:flutter/material.dart';
import 'package:flutterapp/common/base/base_mode.dart';
import 'package:flutterapp/common/base/base_page.dart';
import 'package:flutterapp/common/base/base_provider.dart';
import 'package:flutterapp/common/constant/api.dart';
import 'package:flutterapp/common/util/router_helpe_utils.dart';
import 'package:flutterapp/common/page/webview_page.dart';
import 'package:flutterapp/common/widget/banner_view.dart';
import 'package:flutterapp/common/widget/easy_ink_well.dart';
import 'package:flutterapp/common/widget/favorite_button_widget.dart';
import 'package:flutterapp/home/my_drawer.dart';
import 'package:flutterapp/home/entity/article_data_bean.dart';
import 'package:flutterapp/home/entity/home_article_top_entity.dart';
import 'package:flutterapp/http/http_utils.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'entity/home_article_list_entity.dart';
import 'entity/home_banner_entity.dart';

/// 首页
class HomePage extends StatefulWidget {
  final String title;

  HomePage(this.title);

  @override
  State<StatefulWidget> createState() {
    return HomePageState();
  }
}

class HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  ScrollController _controller = ScrollController();

  /// 是否显示右下角按钮
  bool showFloatBtn = false;

  double initOffSet = 0.0;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return BaseProvider<HomeModel>(
        model: HomeModel(),
        modelBuilder: (context, model) {
          return BasePage(
            title: widget.title,
            drawer: MyDrawer(),
            backgroundColor: Colors.grey,
            child: Container(
              color: Colors.grey[100],
              child: SmartRefresher(
                enablePullDown: true,
                enablePullUp: true,
                header: ClassicHeader(),
                footer: ClassicFooter(),
                controller: model._refreshController,
                onRefresh: () {
                  model.reFreshData();
                },
                onLoading: () {
                  model.loadMoreData();
                },
                child: ListView.builder(
                    controller: _controller,
                    itemCount: model._articleList.length + 1,
                    itemBuilder: (BuildContext context, int index) {
                      return index == 0
                          ? _HomeBannerView()
                          : getListViewItemWidget(
                              model._articleList[index - 1]);
                    }),
              ),
            ),
            floatingActionButton: Visibility(
              visible: showFloatBtn,
              child: FloatingActionButton(
                child: Icon(Icons.arrow_upward),
                backgroundColor: Theme.of(context).primaryColor,
                onPressed: () {
                  //返回到顶部时执行动画
                  _controller.animateTo(.0,
                      duration: Duration(milliseconds: 1500),
                      curve: Curves.ease);
                },
              ),
            ),
          );
        });
  }

  @override
  void initState() {
    super.initState();

    _controller.addListener(() {
      //通过前后两次数据对比确定滑动方向

      if (_controller.offset - initOffSet > 0 && showFloatBtn == false) {
        //向上滑动且按钮没有显示时，刷新显示按钮
        showFloatBtn = true;
        setState(() {});
      } else if (_controller.offset - initOffSet < 0 && showFloatBtn) {
        //向下滑动且按钮没有显示时，刷新显示按钮
        showFloatBtn = false;
      }

      //记录位置
      initOffSet = _controller.offset;
      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();

    _controller.dispose();
  }

  Widget getListViewItemWidget(ArticleDataBean homeArticleDataBean) {
    return EasyInkWell(
      margin: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      color: Colors.white,
      radius: 8,
      child: Container(
        padding: EdgeInsets.all(8),
        child: Row(
          children: <Widget>[
            Center(
              child: FavoriteButtonWidget(
                isFavorite: homeArticleDataBean.collect ?? false,
                id: homeArticleDataBean.id,
              ),
            ),
            Expanded(
                child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  homeArticleDataBean.title ?? '',
                  style: TextStyle(
                      fontWeight: FontWeight.w700,
                      color: Colors.black,
                      fontSize: 15.0),
                ),
                SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: Container(
                    width: 500,
                    child: Row(
                      children:
                          getListViewItemBottomWidget(homeArticleDataBean),
                    ),
                    padding:
                        EdgeInsets.symmetric(vertical: 5.0, horizontal: 0.0),
                  ),
                )
              ],
            ))
          ],
        ),
      ),
      onTap: () {
        RouteHelpUtils.push(
            context,
            WebViewPage(
              url: homeArticleDataBean.link,
              title: homeArticleDataBean.title,
              des: homeArticleDataBean.desc,
            ));
      },
    );
  }

  /// 获取ListView的子view布局中底部的详情组件（如:作者、分类、时间等）
  List<Widget> getListViewItemBottomWidget(
      ArticleDataBean homeArticleDataBean) {
    var tags = <Widget>[];
    var spaceWidget = Container(
      width: 6.0,
    );

    ///开始创建组件数组
    /// 类型为1的为置顶文章，fresh为true的为最新文章,组件顺序按照置顶-新-tags顺序来
    if (homeArticleDataBean.type == 1) {
      //置顶
      Widget tag = DecoratedBox(
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 1.0, horizontal: 3.0),
          child: Text("置顶",
              style: TextStyle(fontSize: 10.0, color: Colors.red[400])),
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(3.0),
          border: Border.all(color: Colors.red[400]!, width: 1.0),
          color: Colors.white,
          shape: BoxShape.rectangle,
        ),
      );
      tags.add(tag);
    }
    if (homeArticleDataBean.fresh == true) {
      //最新
      Widget tag = DecoratedBox(
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 1.0, horizontal: 3.0),
          child: Text("新", style: TextStyle(fontSize: 10.0, color: Colors.red)),
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(3.0),
          border: Border.all(color: Colors.red, width: 1.0),
          color: Colors.white,
          shape: BoxShape.rectangle,
        ),
      );

      ///添加间距
      if (tags.length > 0) {
        tags.add(spaceWidget);
      }

      ///添加组件
      tags.add(tag);
    }
    if (homeArticleDataBean.tags != null &&
        (homeArticleDataBean.tags?.length ?? 0) > 0) {
      //tags中的
      for (HomeArticleDataTag tag in homeArticleDataBean.tags!) {
        Widget tempTag = DecoratedBox(
          child: Padding(
            padding: EdgeInsets.symmetric(vertical: 1.0, horizontal: 3.0),
            child: Text(tag.name ?? '',
                style: TextStyle(fontSize: 10.0, color: Colors.green)),
          ),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(3.0),
            border: Border.all(color: Colors.green, width: 1.0),
            color: Colors.white,
            shape: BoxShape.rectangle,
          ),
        );

        Widget listener = GestureDetector(
          child: tempTag,
          onTap: () {
            RouteHelpUtils.push(
                context,
                WebViewPage(
                  url: API.baseUrl + (tag.url ?? ''),
                  title: tag.name,
                ));
          },
        );

        ///添加间距
        if (tags.length > 0) {
          tags.add(spaceWidget);
        }

        ///添加组件
        tags.add(listener);
      }
    }

    List<TextSpan> desTS = [];

    ///分享人
    if (homeArticleDataBean.shareUser != null &&
        homeArticleDataBean.shareUser!.isNotEmpty) {
//      desc += "  分享人: ${homeArticleDataBean.shareUser}";
      TextSpan shareUserTS = TextSpan(
          text: "  分享人: ",
          style: TextStyle(color: Colors.grey),
          children: [
            TextSpan(
              text: homeArticleDataBean.shareUser,
              style: TextStyle(color: Colors.black),
            )
          ]);
      desTS.add(shareUserTS);
    }

    ///作者
    if (homeArticleDataBean.author != null &&
        homeArticleDataBean.author!.isNotEmpty) {
//      desc += "  作者: ${homeArticleDataBean.author}";
      TextSpan authorTS = TextSpan(
          text: "  作者: ",
          style: TextStyle(color: Colors.grey),
          children: [
            TextSpan(
              text: homeArticleDataBean.author,
              style: TextStyle(color: Colors.black),
            )
          ]);
      desTS.add(authorTS);
    }

    ///分类
    if (homeArticleDataBean.superChapterName != null &&
        homeArticleDataBean.superChapterName!.isNotEmpty &&
        homeArticleDataBean.chapterName != null &&
        homeArticleDataBean.chapterName!.isNotEmpty) {
//      desc +=
//          "  分类: ${homeArticleDataBean.superChapterName}/${homeArticleDataBean.chapterName}";
      TextSpan chapterTS = TextSpan(
          text: "  分类: ",
          style: TextStyle(color: Colors.grey),
          children: [
            TextSpan(
              text:
                  "${homeArticleDataBean.superChapterName}/${homeArticleDataBean.chapterName}",
              style: TextStyle(color: Colors.black),
            )
          ]);
      desTS.add(chapterTS);
    }

    ///时间
    if (homeArticleDataBean.niceDate != null &&
        homeArticleDataBean.niceDate!.isNotEmpty) {
//      desc += "  时间: ${homeArticleDataBean.niceDate}";
      TextSpan timeTS = TextSpan(
          text: "  时间: ",
          style: TextStyle(color: Colors.grey),
          children: [
            TextSpan(
              text: homeArticleDataBean.niceDate,
              style: TextStyle(color: Colors.black),
            )
          ]);
      desTS.add(timeTS);
    }

    Widget tempDes = Expanded(
      child: Text.rich(
        TextSpan(children: desTS),
        style: TextStyle(fontSize: 10.0, color: Colors.grey),
        overflow: TextOverflow.ellipsis,
      ),
    );

    ///添加间距
    if (tags.length > 0) {
      tags.add(spaceWidget);
    }

    ///添加组件
    tags.add(tempDes);
    return tags;
  }

  @override
  bool get wantKeepAlive => true;
}

/// 轮播图组件
class _HomeBannerView extends StatelessWidget {
  const _HomeBannerView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 获取banner数据列表
    List<HomeBannerEntityData?>? data =
        context.watch<HomeModel>()._homeBannerEntity?.data;
    // pageview控制器
    return BannerView<HomeBannerEntityData?>(
        data: data ?? [],
        indicatorMargin: EdgeInsets.only(bottom: 12),
        autoTime: Duration(seconds: 5),
        child: (value) {
          return InkWell(
            onTap: () {
              RouteHelpUtils.push(
                  context,
                  WebViewPage(
                    url: value?.url,
                    title: value?.title,
                    des: value?.desc,
                  ));
            },
            child: Container(
              margin: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular((10.0)), // 圆角度
                image: DecorationImage(
                  image: NetworkImage(value?.imagePath ?? ''),
                  fit: BoxFit.fill,
                ),
              ),
            ),
          );
        });
  }
}

/// 数据模型
class HomeModel extends BaseModel {
  /// 轮播图数据
  HomeBannerEntity? _homeBannerEntity;

  /// 文章列表数据集合
  List<ArticleDataBean> _articleList = <ArticleDataBean>[];

  /// 是否展示网络出错页面
  bool isVisibleErrorPage = false;

  /// 网络出错页面提示信息
  String errorPageMsg = "";

  ///默认页码
  int curPageNum = 0;

  /// 刷新控制器
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  Future<bool> init() {
    return Future.wait<bool>([
      initBannerData(),
      initArticleListData(),
    ]).then((value) => value.contains(true));
  }

  /// 从网络获取轮播图数据
  Future<bool> initBannerData() {
    return HttpUtils.getInstance()
        .get<HomeBannerEntity>(API.homeBanner, isNeedCache: true)
        .then((value) {
      if (value != null) {
        //设置数据
        _homeBannerEntity = value;
        return true;
      } else {
        return false;
      }
    });
  }

  /// 从网络获取文章列表数据
  Future<bool> initArticleListData() async {
    //设置当前页为 0
    curPageNum = 0;

    ///获取置顶文章列表数据
    HomeArticleTopEntity? homeArticleTopEntity =
        await HttpUtils.getInstance().get<HomeArticleTopEntity>(
      API.homeArticleTop,
      isNeedCache: true,
    );

    ///获取文章列表数据
    HomeArticleListEntity? homeArticleListEntity =
        await HttpUtils.getInstance().get<HomeArticleListEntity>(
      API.getHomeArticleList(curPageNum),
      isNeedCache: true,
    );

    // 清空集合
    _articleList.clear();

    if (homeArticleTopEntity == null && homeArticleListEntity == null) {
      return false;
    } else {
      //置顶文章数据
      _articleList.addAll(homeArticleTopEntity?.data ?? []);
      //文章数据
      _articleList.addAll(homeArticleListEntity?.data?.datas ?? []);

      return true;
    }
  }

  /// 加载更多请求数据
  void loadMoreData() {
    ///获取文章列表数据
    curPageNum++;
    HttpUtils.getInstance().get<HomeArticleListEntity>(
        API.getHomeArticleList(curPageNum), onSuccess: (homeArticleListEntity) {
      if (homeArticleListEntity.data?.datas == null ||
          homeArticleListEntity.data!.datas!.isEmpty) {
        _refreshController.loadNoData();
      } else {
        _articleList.addAll(homeArticleListEntity.data!.datas!);
        _refreshController.loadComplete();
        notifyListeners();
      }
    }, onFailure: (msg, stack) {
      _refreshController.loadFailed();
    });
  }

  /// 刷新数据
  void reFreshData() {
    curPageNum = 0;
    Future.wait([
      initBannerData(),
      initArticleListData(),
    ]).then((value) {
      if (value.contains(false)) {
        _refreshController.refreshFailed();
      } else {
        _refreshController.refreshCompleted();
      }

      notifyListeners();
    });
  }

  @override
  void dispose() {
    super.dispose();

    _refreshController.dispose();
  }
}
